<?php
/**
 * Created by PhpStorm.
 * User:
 * Date: 15/9/9
 * Time: 下午4:06
 */

class ActivityLoginController extends BaseController {
    /*
      * @Author:      kc
     * @DateTime:    2017-02-22 14:30:32
     * @Description: 用户登录或注册
     * */
    public function login()
    {
        $validator = Validator::make(Input::all(),
            array(
                'phone' => 'required',
                'check_code' => 'required',
                'register_source_id' => 'required',
            )
        );
        do {
            if ($validator->fails()) {
                $response = Lang::get("error.args_error_10000");
                $response["result"] = $validator->messages()->all();
                break;
            }
            $time_out_default = Config::get("user.check_code_time_out");
            //默认手机号固定验证码
            $cc = UserCheckCode::where('phone','13000000999')->first();
            if($cc){
                UserCheckCode::where('phone','13000000999')->update(array('check_code'=> '1234','out_time_at'=>Common::num2DateTime(time() + $time_out_default)));
            }else{
                //记录数据库
                $data = array(
                    'phone' => '13000000999',
                    'area' => '010',
                    'check_code' => '1234',
                    'created_at' => Common::num2DateTime(time()),
                    'out_time_at' => Common::num2DateTime(time() + $time_out_default),
                    'send_id' => 1,
                );
                try {
                    UserCheckCode::insCheckCode($data);
                } catch (Exception $e) {
                    Log::error("error", array("system" => "wechat2.0" ,"event" => "login_sms_check_code", 'input' =>Input::all() ,"exception" => $e));
                    $response = Lang::get("error.user_sms_check_code_create_error_1002");
                    break;
                }
            }
            $area = '010';
            $record = UserCheckCode::getCheckCode(Input::get('phone'),$area);
            if (is_null($record)) { //没有记录
                $response = Lang::get("error.user_login_checkcode_null_10004");
                break;
            }
            //校验是否超过时限
            if (time() > Common::datetime2Num($record->out_time_at)) {
                $response = Lang::get("error.user_login_checkcode_timeout_10005");
                break;
            }
            //校验验证码是否正确
            if ($record->check_code != Input::get('check_code')) {
                $response = Lang::get("error.user_login_checkcode_error_10006");
                break;
            }
            $wechat = Users::getUser(Input::get('phone'));
            if (is_null($wechat)) {
                try{
                        $wechat = new Users();
                        $wechat->phone = Input::get('phone');
                        $wechat->status = 1;
                        $wechat->register_source_id = Input::get('register_source_id');//1-微站 2-app 14-门店
                        $wechat->real_name = '';
                        $wechat->sex = 0;
                        $wechat->area = '010';
                        $wechat->type = 1;
                        $wechat->activate = 0;
                        $wechat->nickname = '';
                        $wechat->heading_img = '';
                        $wechat->member = Config::get('user.def_member');
                        $wechat->save();

                }catch (Exception $e){
                    Log::error("error", array("system" => "wechat2.0" ,"event" => "login", 'input' =>Input::all() ,"exception" => $e));
                    $response = Lang::get("error.login_create_token_error_21005");
                    break;
                }
            }
            if($wechat->status == 2){   //用户状态 冻结
                $response = Lang::get('error.user_frozen_error_21002');
                break;
            }
            if($wechat->status == 0){   //用户状态 关闭
                $response = Lang::get('error.user_type_21010');
                break;
            }
            if($wechat->type == 2){     //禁止企业用户登录
                $response = Lang::get('error.user_type_21009');
                break;
            }
            //如果发现此用户是老用户，且未激活 给优惠券 且再激活
            if($wechat->type == 1 && $wechat->activate == 0){
                //记录是否是新老用户
                $is_new = KingGloryUser::where("user_id",$wechat->id)->first();
                if(is_null($is_new)){
                    $new_user = new KingGloryUser();
                    $new_user->user_id = $wechat->id;
                    $new_user->phone = $wechat->phone;
                    $new_user->new = '新用户';
                    $new_user->type = Input::get('type',1);
                    $new_user->created_at = date("Y-m-d H:i:s",time());
                    $new_user->updated_at = date("Y-m-d H:i:s",time());
                    $new_user->save();
                }

                //注册送券
                if(Config::get("config.king_register_coupons") == 1){
                    
                    $activity = Coupons::getNewUserRegister(Config::get('config.king_activity_id'),$response);
                    if(!is_null($activity)){
                        foreach ($activity as  $v) {
                            $coupon_base_info = Coupons::getCouponBaseInfo($v->coupon_base_info_id);
                            if (!$coupon_base_info) {
                                break;
                            }
                            if ($coupon_base_info->status == 0) {
                                break;
                            }
                            if ($coupon_base_info->date_type == 0 && strtotime($coupon_base_info->end_date.' 23:59:59') < strtotime(date('Y-m-d H:i:s', time()))) { //起止时间
                                break;
                            }
                            $coupon_whether_exist = Coupons::getCouponOther($v->coupon_base_info_id);
                            if (!is_null($coupon_whether_exist)) {
                                $coupons = Coupons::find($coupon_whether_exist->id);
                                $coupons->status = 2;
                                $coupons->received_user_id = $wechat->id;
                                $coupons->get_time = date("Y-m-d H:i:s", time());
                                if ($coupon_base_info->date_type == 1) { //顺延日期
                                    $coupons->end_date = date("Y-m-d", strtotime("+" . $coupon_base_info->date_num . " day"));
                                }
                                $coupons->save();
                                //友盟优惠券到账消息推送
                                if(Config::get('u_meng_push.is_open_u_meng_push') ==1 && Input::get('register_source_id') ==2){
                                    Orders::notifyMsg($wechat->id,2,'优惠券已到账','您的'.($coupon_base_info->amount/100).'元优惠券已到帐');
                                }
                            }
                        }
                    }
                }
                $wechat->activate = 1;
                $wechat->save();
            }else{
                //记录是否是新老用户
                $is_new = KingGloryUser::where("user_id",$wechat->id)->first();
                if(is_null($is_new)){
                    $new_user = new KingGloryUser();
                    $new_user->user_id = $wechat->id;
                    $new_user->phone = $wechat->phone;
                    $new_user->new = '老用户';
                    $new_user->type = Input::get('type',1);
                    $new_user->created_at = date("Y-m-d H:i:s",time());
                    $new_user->updated_at = date("Y-m-d H:i:s",time());
                    $new_user->save();
                }
            }

//            if ($wechat->type == 1 && $wechat->activate == 1) {
//
//                //登陆送券
//                if(Config::get("config.king_login_coupons") == 1){
//
//                    $activity = Coupons::getNewUserRegister(Config::get('config.king_activity_login_id'),$response);
//                    if(!is_null($activity)){
//                        foreach ($activity as  $v) {
//                            $coupon_base_info = Coupons::getCouponBaseInfo($v->coupon_base_info_id);
//                            if (!$coupon_base_info) {
//                                break;
//                            }
//                            if ($coupon_base_info->status == 0) {
//                                break;
//                            }
//                            if ($coupon_base_info->date_type == 0 && strtotime($coupon_base_info->end_date.' 23:59:59') < strtotime(date('Y-m-d H:i:s', time()))) { //起止时间
//                                break;
//                            }
//                            $user_coupons = coupons::isCoupons($v->coupon_base_info_id,$wechat->id);
//                            if (!is_null($user_coupons)) { //如果已经领过一次了，就不能在领了
//                                break;
//                            }
//
//                            $coupon_whether_exist = Coupons::getCouponOther($v->coupon_base_info_id);
//                            if (!is_null($coupon_whether_exist)) {
//                                $coupons = Coupons::find($coupon_whether_exist->id);
//                                $coupons->status = 2;
//                                $coupons->received_user_id = $wechat->id;
//                                $coupons->get_time = date("Y-m-d H:i:s", time());
//                                if ($coupon_base_info->date_type == 1) { //顺延日期
//                                    $coupons->end_date = date("Y-m-d", strtotime("+" . $coupon_base_info->date_num . " day"));
//                                }
//                                $coupons->save();
//                                //友盟优惠券到账消息推送
//                                if(Config::get('u_meng_push.is_open_u_meng_push') ==1 && Input::get('register_source_id') ==2){
//                                    Orders::notifyMsg($wechat->id,2,'优惠券已到账','您的'.($coupon_base_info->amount/100).'元优惠券已到帐');
//                                }
//                            }
//                        }
//                    }
//                }
//                $wechat->save();
//            }
            
            try{
                $token="";
                $find_token = UserTokens::where('user_id',$wechat->id)->first();
                if(!is_null($find_token)){ //有token 判断token是否过期
                    if(strtotime($find_token->out_time_at) < time()){//说明过期了
                        UserTokens::where('user_id',$wechat->id)->delete();
                        $user_token = new UserTokens;
                        $user_token->user_id = $wechat->id;
                        $user_token->token = md5(Input::get('phone').time().rand(0,100));
                        $user_token->created_at = Common::num2DateTime(time());
                        $user_token->out_time_at = Common::num2DateTime(time() + Config::get("user.token_time_out"));
                        $user_token->save();
                        $token=$user_token->token;
                    }else{
                        $token=$find_token->token;
                    }
                }else{
                    $user_token = new UserTokens;
                    $user_token->user_id = $wechat->id;
                    $user_token->token = md5(Input::get('phone').time().rand(0,100));
                    $user_token->created_at = Common::num2DateTime(time());
                    $user_token->out_time_at = Common::num2DateTime(time() + Config::get("user.token_time_out"));
                    $user_token->save();
                    $token=$user_token->token;
                }

            } catch (Exception $e){
                Log::error("error", array("system" => "wechat2.0" ,"event" => "login", 'input' =>Input::all() ,"exception" => $e));
                $response = Lang::get("error.login_create_token_error_21005");
                break;
            }
            $response = array(
                'code' => 0,
                'msg' => 'ok',
                'result' =>array(
                    'id'=> $wechat->id,
                    'token' => $token,
                    'phone' => $wechat->phone,
                    'real_name' => $wechat->real_name,
                    'sex' => $wechat->sex,
                    'area' => $wechat->area,
                    'remark' => $wechat->remark,
                    'type' => $wechat->type,
                    'status' =>$wechat->status,
                    'nickname' => $wechat->nickname,
                    'birthday' => $wechat->birthday,
                    'heading_img' =>  $wechat->heading_img,
                    'heading_img_url' =>  Config::get('config.heading_img_url'),
                )
            );

        } while (false);
        Log::info("info", array("system" => "wechat2.0" ,"event" => "login", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
}
